package com.wdm.sms.service.huawei.impl;

import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.*;
import com.wdm.sms.commonutil.config.huawei.HweiOBSConfig;
import com.wdm.sms.commonutil.utils.r.R;
import com.wdm.sms.service.huawei.HweiYunOBSService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

/**
 * @ClassName: HweiYunOBSServiceImpl
 * @Description: 华为云OBS服务业务层
 * @author: wudaiming
 * @date: 2023/3/21
 * @version: 1.0
 */
@Slf4j
@Service
public class HweiYunOBSServiceImpl implements HweiYunOBSService {

    @Autowired
    private HweiOBSConfig hweiOBSConfig;

    @Override
    public boolean delete(String objectKey) {
        ObsClient obsClient = null;
        try {
            // 创建ObsClient实例
            obsClient = hweiOBSConfig.getInstance();
            // obs删除
            obsClient.deleteObject(hweiOBSConfig.getBucketName(),objectKey);
        } catch (ObsException e) {
            log.error("obs删除保存失败", e);
        } finally {
            hweiOBSConfig.destroy(obsClient);
        }
        return true;
    }

    @Override
    public boolean delete(List<String> objectKeys) {
        ObsClient obsClient = null;
        try {
            obsClient = hweiOBSConfig.getInstance();
            DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(hweiOBSConfig.getBucketName());
            objectKeys.forEach(x -> deleteObjectsRequest.addKeyAndVersion(x));
            // 批量删除请求
            obsClient.deleteObjects(deleteObjectsRequest);
            return true;
        } catch (ObsException e) {
            log.error("obs删除保存失败", e);
        } finally {
            hweiOBSConfig.destroy(obsClient);
        }
        return false;
    }

    @Override
    public String fileUpload(MultipartFile uploadFile, String objectKey) {
        ObsClient obsClient = null;
        try {
            String bucketName = hweiOBSConfig.getBucketName();
            obsClient = hweiOBSConfig.getInstance();
            // 判断桶是否存在
            boolean exists = obsClient.headBucket(bucketName);
            if(!exists){
                // 若不存在，则创建桶
                HeaderResponse response = obsClient.createBucket(bucketName);
                log.info("创建桶成功:{}", response.getRequestId());
            }
            InputStream inputStream = uploadFile.getInputStream();
            long available = inputStream.available();
            PutObjectRequest request = new PutObjectRequest(bucketName,objectKey,inputStream);

            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(available);
            request.setMetadata(objectMetadata);
            // 设置对象访问权限为公共读
            request.setAcl(AccessControlList.REST_CANNED_PUBLIC_READ);
            PutObjectResult result = obsClient.putObject(request);

            // 读取该已上传对象的URL
            log.info("已上传对象的URL:{}", result.getObjectUrl());
            return URLDecoder.decode(result.getObjectUrl(), "UTF-8");
        } catch (ObsException e) {
            log.error("obs上传失败", e);
        } catch (IOException e) {
            log.error("上传失败", e);
        } finally {
            hweiOBSConfig.destroy(obsClient);
        }
        return null;
    }

    @Override
    public InputStream fileDownload(String objectKey) {
        ObsClient obsClient = null;
        try {
            String bucketName = hweiOBSConfig.getBucketName();
            obsClient = hweiOBSConfig.getInstance();
            ObsObject obsObject = obsClient.getObject(bucketName, objectKey);
            return obsObject.getObjectContent();
        } catch (ObsException e) {
            log.error("obs文件下载失败", e);
        } finally {
            hweiOBSConfig.destroy(obsClient);
        }
        return null;
    }

    @Override
    public R previewFile(HttpServletRequest request, HttpServletResponse response, String objectKey) throws IOException{
        try {
            //解决输入栏objectKey中文乱码
            objectKey= URLDecoder.decode(objectKey, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 创建ObsClient实例
        ObsClient obsClient = null;
        try {
            String bucketName = hweiOBSConfig.getBucketName();
            obsClient = hweiOBSConfig.getInstance();
            ObsObject obsObject = obsClient.getObject(bucketName, objectKey);
            // 读取对象内容
            InputStream inStream = obsObject.getObjectContent();
            // 设置输出的格式
            response.setContentType( "application/pdf" );
            OutputStream outputStream = response.getOutputStream();
            int count;
            byte[] buffer = new byte[1024 * 1024];
            while ((count =inStream.read(buffer)) != -1){
                outputStream.write(buffer, 0,count);
            }
            outputStream.flush();
        } catch (ObsException e) {
            log.error("预览文件获取失败", e);
        } finally {
            hweiOBSConfig.destroy(obsClient);
        }
        return null;
    }
}